/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
import React, { Component } from 'react';
import { ImageBackground, TouchableOpacity, View, Image, Alert, ActivityIndicator, Text } from 'react-native';
import styles from './styles';
import getUniqueFileUris from './getFileList';
import GetjsonData, { Getjsonwords } from '../../services/getJsonData';
import { NewWord } from '../../services/getJsonData';
import { store } from '../../store/store';

const VideoPlayer = React.lazy(() => import('./videoplay'));  // 确保路径和文件名正确
interface State {
  number: number;
  isPlaying: boolean;
  text: string;
  huozhong:string[];
  ziyuan:NewWord[];
  fileUris: { [key: string]: string};
  unit:String;
}

export default class Learn extends Component<{unit: string}, State> {
  state: State = {
    number: 0,
    isPlaying: false,
    huozhong:[],
    ziyuan:[],
    text: '',
    fileUris: {},
    unit:'unit0',
  };
  async  getinfo(unit:string) {
    try {
        // 使用 Promise.all 同时等待三个 Promise 的解决
        const result = await Promise.all([
            GetjsonData(unit),
            Getjsonwords(unit),
            getUniqueFileUris(),
        ]);
        return result;
        // 在这里，huozhong, ziyuan, 和 fileUris 分别包含了三个异步操作的结果
        // 您可以继续使用这些结果进行后续操作
        // ...

    } catch (error) {
        // 如果任何一个 Promise 被拒绝，这里将捕获错误
        console.error(error);
    }
}
async componentDidMount() {
  const handleStoreChange = () => {
    const state = store.getState().rootReducer;
    if (state.IsloadingReducer.isLoadingStatus === 'false') {
      const { unit } = this.props.route.params;

      // 使用 Promise.all 简化异步调用
      this.getinfo(unit)
        .then(([huozhong, ziyuan, fileUris]) => {
          this.setState({ unit, huozhong, ziyuan, fileUris }, () => {
            if (huozhong.length > 0) {
              this.setState({ text: huozhong[0] });
            }
          });
        })
        .catch((error) => console.error('Error fetching info:', error));
    }
  };

    // 订阅 Redux store 的变化
    this.unsubscribe = store.subscribe(() => {
      console.log('Store state changed');
      handleStoreChange();
    });

    // 初始调用一次，以同步当前状态
    handleStoreChange();
  }
  // 组件卸载时取消订阅
componentWillUnmount() {
  if (this.unsubscribe) {
    this.unsubscribe();
  }
}


  playsound = () => {
     // 触发视频播放或重新加载
   this.setState({isPlaying:true});
  };

  changecharacter1 = () => {
    this.setState((prevState) => {
      // console.log(prevState.number);
      if (prevState.number === 0) {return null;} // 如果 number 为 1，不执行任何操作
      const newNumber = prevState.number - 1;
      return {
        number: newNumber,
        text: this.state.huozhong[newNumber] || prevState.text,
      };
    });
  };

  changecharacter2 = () => {
    this.setState((prevState) => {
      // console.log(prevState.number);
      if (prevState.number === this.state.huozhong.length - 1) {return null;} // 如果 number 为 4，不执行任何操作
      const newNumber = prevState.number + 1;
      return {
        number: newNumber,
        text: this.state.huozhong[newNumber] || prevState.text,
      };
    });
  };

  render() {
    return (
      <ImageBackground
        resizeMode="stretch"
        style={styles.constiner}
        source={require('../../src/image/learn_background.jpg')}
      >
        <TouchableOpacity
          style={{ position: 'absolute', width: 150, height: 100, justifyContent: 'center', top: 20, left: 10 }}
          onPress={() => {
            console.log('学习');
            if (this.props.navigation) {
              this.props.navigation.navigate('select'); // 确保 navigation 属性可用
            }
          }}
        >
          <Image source={require('../../src/image/UI/learn_back_planet.png')} style={{ width: 150, height: 100 }} />
          <Image source={require('../../src/image/UI/learn_back.png')} style={{ position: 'absolute', width: 80, height: 40, justifyContent: 'center', top: 30, left: 30, resizeMode: 'stretch' }} />
        </TouchableOpacity>

        <View style={{flexDirection: 'row',top:20, justifyContent: 'center'}}>
          <TouchableOpacity
            style={{flex: 1,top:-30, justifyContent: 'center', alignItems: 'flex-end', marginRight: 110}}
            onPress={this.changecharacter1}
          >
            <Image source={require('../../src/image/UI/adventure_back.png')}
                   style={{width: 40, height: 60, resizeMode: 'stretch'}} />
          </TouchableOpacity>
          <View style={{position: 'absolute', flex: 1, justifyContent: 'center', alignItems: 'center'}}>
       { store.getState().rootReducer.IsloadingReducer.isLoadingStatus === 'true' ? (<View style={styles.loading}>
          <ActivityIndicator size="large" color="#0000ff" style={{alignSelf: 'center',top: 70}} />
          <Text style={{alignSelf: 'center'}}>下载中...</Text>
        </View>) : (null)}
      </View>


      <React.Suspense fallback={<View style={{backgroundColor:'red',width:1000,height:1000}}><Text>sss</Text></View>}>
      <VideoPlayer text={this.state.fileUris[this.state.text]}  isPlaying={this.state.isPlaying} />
             </React.Suspense>
          <TouchableOpacity
            style={{flex: 1, top:-30,justifyContent: 'center', alignItems: 'flex-start', marginLeft:110 }}
            onPress={this.changecharacter2}
          >
            <Image source={require('../../src/image/UI/adventure_next.png')}
                   style={{width: 40, height: 60, resizeMode: 'stretch'}} />
          </TouchableOpacity>
        </View>
        <View style={{
          top:200,
          alignItems: 'center',
          padding: 20,
        }}>
          <TouchableOpacity  onPress={()=>{ this.setState({isPlaying:!this.state.isPlaying});
          console.log('result');


            this.props.navigation.navigate('warm',{unit: this.state.unit,strc: 'practise',page: 1  });
            }}>

            <Image source={require('../../src/image/UI/practise.png')}
                   style={{ width: 80,bottom:50, height: 40, resizeMode: 'stretch' }} />
          </TouchableOpacity>
        </View>
      </ImageBackground>
    );
  }
}